/**
 * 截流装饰器
 *    目的: 每隔一段时间, 执行一次原函数
 *
 *    设计思路:
 *      1. 包装原函数
 *      2. 不能用 Timeout 调用包装, 因为 Timeout 优先级低
 *      3.
 *      4.
 * */
function throttle(func, interval) {
  let timeout = null;

  return function () {
    const context = this,
      args = arguments;

    const later = function () {
      timeout = null;
    };

    if (!timeout) {
      func.apply(context, args);
      timeout = setTimeout(later, interval);
    }

    console.log(`被装饰的函数执行次数`);
  };
}

// 被装饰的函数
function doSomething() {
  console.log("我想干啥就干啥");
}

// 装饰后的函数
const doSomethingThrottled = throttle(doSomething, 400);

// 连续调用
const invokeConstantly = function () {
  const length = 1000;
  let count = 1;
  const timer = setInterval(() => {
    doSomethingThrottled();
    if (++count > length) clearInterval(timer);
  }, 10);
};

invokeConstantly();
